#include "comm.hpp"

// 通过共享内存通信
void client1()
{
    key_t key = GetKey();
    cout << "key: " << ToHex(key) << endl;
    int shmid = GetShm(key);
    cout << "client 连接上共享内存……, id: " << shmid << endl;
    sleep(5);
    char *str = (char *)shmat(shmid, nullptr, 0);
    // 进行通信
    char c = 'a';
    for (; c <= 'z'; c++)
    {
        // 对共享内存对应的地址空间进行写入
        str[c - 'a'] = c;
        cout << "write: " << c << " done" << endl;
        sleep(2);
    }
    shmdt(str);
}
// 共享内存 + 命名管道通信
void client2()
{
    key_t key = GetKey();
    cout << "key: " << ToHex(key) << endl;
    int shmid = GetShm(key);
    cout << "client 连接上共享内存……, id: " << shmid << endl;
    sleep(5);
    char *str = (char *)shmat(shmid, nullptr, 0);
    // 进行通信
    int r_open = open("fifo", O_WRONLY);

    char c = 'a';
    for (; c <= 'z'; c++)
    {
        // 对共享内存对应的地址空间进行写入
        str[c - 'a'] = c;
        cout << "write: " << c << " done" << endl;
        write(r_open, str, sizeof(str));
        sleep(2);
    }
    close(r_open);
    shmdt(str);
}

int main()
{
    client2();
}